package com.notmaker.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.notmaker.entity.User;
import com.notmaker.service.UserService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Controller
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录（web端使用，需要验证码）
     * @param loginRequest 登录请求参数
     * @param session HttpSession
     * @return 登录结果
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginRequest, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        String role = loginRequest.get("role");
        String captcha = loginRequest.get("captcha");
        
        // 参数校验
        if (username == null || username.isEmpty()) {
            result.put("success", false);
            result.put("message", "用户名不能为空");
            return result;
        }
        
        if (password == null || password.isEmpty()) {
            result.put("success", false);
            result.put("message", "密码不能为空");
            return result;
        }
        
        if (role == null || role.isEmpty()) {
            result.put("success", false);
            result.put("message", "请选择登录身份");
            return result;
        }
        
        if (captcha == null || captcha.isEmpty()) {
            result.put("success", false);
            result.put("message", "验证码不能为空");
            return result;
        }
        
        // 验证验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return result;
        }
        
        // 验证码使用后立即清除
        session.removeAttribute("captcha");
        
        // 先查询用户是否存在
        QueryWrapper<User> checkWrapper = new QueryWrapper<>();
        checkWrapper.eq("username", username);
        checkWrapper.eq("role", role);
        User existUser = userService.getOne(checkWrapper);
        
        // 如果用户存在，检查状态
        if (existUser != null && "禁用".equals(existUser.getStatus())) {
            result.put("success", false);
            result.put("message", "该账号已被禁用，无法登录");
            return result;
        }
        
        // 调用登录服务
        User user = userService.login(username, password, role);
        
        if (user != null) {
            // 登录成功，移除密码字段
            user.setPassword(null);
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", user);
        } else {
            result.put("success", false);
            result.put("message", "用户名、密码或身份错误");
        }
        
        return result;
    }

    /**
     * 微信小程序用户登录（不需要验证码）
     * @param loginRequest 登录请求参数
     * @return 登录结果
     */
    @PostMapping("/wechat/login")
    public Map<String, Object> wechatLogin(@RequestBody Map<String, String> loginRequest) {
        Map<String, Object> result = new HashMap<>();
        
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        String role = loginRequest.get("role");
        
        // 参数校验
        if (username == null || username.isEmpty()) {
            result.put("success", false);
            result.put("message", "用户名不能为空");
            return result;
        }
        
        if (password == null || password.isEmpty()) {
            result.put("success", false);
            result.put("message", "密码不能为空");
            return result;
        }
        
        if (role == null || role.isEmpty()) {
            result.put("success", false);
            result.put("message", "请选择登录身份");
            return result;
        }
        
        // 先查询用户是否存在
        QueryWrapper<User> checkWrapper = new QueryWrapper<>();
        checkWrapper.eq("username", username);
        checkWrapper.eq("role", role);
        User existUser = userService.getOne(checkWrapper);
        
        // 如果用户存在，检查状态
        if (existUser != null && "禁用".equals(existUser.getStatus())) {
            result.put("success", false);
            result.put("message", "该账号已被禁用，无法登录");
            return result;
        }
        
        // 调用登录服务
        User user = userService.login(username, password, role);
        
        if (user != null) {
            // 登录成功，移除密码字段
            user.setPassword(null);
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", user);
        } else {
            result.put("success", false);
            result.put("message", "用户名、密码或身份错误");
        }
        
        return result;
    }

    /**
     * 微信小程序用户注册（不需要验证码）
     * @param registerRequest 注册请求参数
     * @return 注册结果
     */
    @PostMapping("/wechat/register")
    public Map<String, Object> wechatRegister(@RequestBody Map<String, String> registerRequest) {
        Map<String, Object> result = new HashMap<>();
        
        String username = registerRequest.get("username");
        String password = registerRequest.get("password");
        String nickname = registerRequest.get("nickname");
        String phone = registerRequest.get("phone");
        String email = registerRequest.get("email");
        
        // 参数校验
        if (username == null || username.isEmpty()) {
            result.put("success", false);
            result.put("message", "用户名不能为空");
            return result;
        }
        
        if (password == null || password.isEmpty()) {
            result.put("success", false);
            result.put("message", "密码不能为空");
            return result;
        }
        
        if (nickname == null || nickname.isEmpty()) {
            result.put("success", false);
            result.put("message", "昵称不能为空");
            return result;
        }
        
        // 检查用户名是否已存在
        if (userService.checkUsernameExists(username)) {
            result.put("success", false);
            result.put("message", "用户名已存在");
            return result;
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setPhone(phone);
        user.setEmail(email);
        
        // 调用注册服务
        boolean success = userService.register(user);
        
        if (success) {
            result.put("success", true);
            result.put("message", "注册成功");
        } else {
            result.put("success", false);
            result.put("message", "注册失败");
        }
        
        return result;
    }

    /**
     * 用户注册（web端使用，需要验证码）
     * @param registerRequest 注册请求参数
     * @param session HttpSession
     * @return 注册结果
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> registerRequest, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        String username = registerRequest.get("username");
        String password = registerRequest.get("password");
        String nickname = registerRequest.get("nickname");
        String phone = registerRequest.get("phone");
        String email = registerRequest.get("email");
        String captcha = registerRequest.get("captcha");
        
        // 参数校验
        if (username == null || username.isEmpty()) {
            result.put("success", false);
            result.put("message", "用户名不能为空");
            return result;
        }
        
        if (password == null || password.isEmpty()) {
            result.put("success", false);
            result.put("message", "密码不能为空");
            return result;
        }
        
        if (nickname == null || nickname.isEmpty()) {
            result.put("success", false);
            result.put("message", "昵称不能为空");
            return result;
        }
        
        if (captcha == null || captcha.isEmpty()) {
            result.put("success", false);
            result.put("message", "验证码不能为空");
            return result;
        }
        
        // 验证验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return result;
        }
        
        // 验证码使用后立即清除
        session.removeAttribute("captcha");
        
        // 检查用户名是否已存在
        if (userService.checkUsernameExists(username)) {
            result.put("success", false);
            result.put("message", "用户名已存在");
            return result;
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setPhone(phone);
        user.setEmail(email);
        
        // 调用注册服务
        boolean success = userService.register(user);
        
        if (success) {
            result.put("success", true);
            result.put("message", "注册成功");
        } else {
            result.put("success", false);
            result.put("message", "注册失败");
        }
        
        return result;
    }

    /**
     * 检查用户名是否已存在
     * @param username 用户名
     * @return 检查结果
     */
    @GetMapping("/checkUsername")
    public Map<String, Object> checkUsername(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        boolean exists = userService.checkUsernameExists(username);
        result.put("exists", exists);
        return result;
    }

    /**
     * 获取测试账号列表
     * @return 测试账号列表
     */
    @GetMapping("/getTestAccounts")
    public Map<String, Object> getTestAccounts() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Map<String, String>> testAccounts = userService.getTestAccounts();
            result.put("success", true);
            result.put("data", testAccounts);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取测试账号失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 根据用户ID获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/getUserInfo")
    public Map<String, Object> getUserInfo(@RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        User user = userService.getUserById(userId);
        if (user != null) {
            // 移除密码字段
            user.setPassword(null);
            result.put("success", true);
            result.put("data", user);
        } else {
            result.put("success", false);
            result.put("message", "用户不存在");
        }
        
        return result;
    }

    /**
     * 更新用户信息
     * @param updateRequest 更新请求参数
     * @return 更新结果
     */
    @PostMapping("/updateUserInfo")
    public Map<String, Object> updateUserInfo(@RequestBody Map<String, Object> updateRequest) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取参数
        Long userId = Long.valueOf(updateRequest.get("id").toString());
        String nickname = (String) updateRequest.get("nickname");
        String avatar = (String) updateRequest.get("avatar");
        String phone = (String) updateRequest.get("phone");
        String email = (String) updateRequest.get("email");
        
        // 参数校验
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户ID不能为空");
            return result;
        }
        
        if (nickname == null || nickname.isEmpty()) {
            result.put("success", false);
            result.put("message", "昵称不能为空");
            return result;
        }
        
        // 创建用户对象
        User user = new User();
        user.setId(userId);
        user.setNickname(nickname);
        user.setAvatar(avatar);
        user.setPhone(phone);
        user.setEmail(email);
        
        // 调用更新服务
        boolean success = userService.updateUserInfo(user);
        
        if (success) {
            // 获取更新后的用户信息
            User updatedUser = userService.getUserById(userId);
            updatedUser.setPassword(null);
            
            result.put("success", true);
            result.put("message", "更新成功");
            result.put("data", updatedUser);
        } else {
            result.put("success", false);
            result.put("message", "更新失败");
        }
        
        return result;
    }

    /**
     * 修改用户密码
     * @param passwordRequest 密码修改请求参数
     * @return 修改结果
     */
    @PostMapping("/changePassword")
    public Map<String, Object> changePassword(@RequestBody Map<String, String> passwordRequest) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取参数
        String userIdStr = passwordRequest.get("userId");
        String oldPassword = passwordRequest.get("oldPassword");
        String newPassword = passwordRequest.get("newPassword");
        
        // 参数校验
        if (userIdStr == null || userIdStr.isEmpty()) {
            result.put("success", false);
            result.put("message", "用户ID不能为空");
            return result;
        }
        
        if (oldPassword == null || oldPassword.isEmpty()) {
            result.put("success", false);
            result.put("message", "旧密码不能为空");
            return result;
        }
        
        if (newPassword == null || newPassword.isEmpty()) {
            result.put("success", false);
            result.put("message", "新密码不能为空");
            return result;
        }
        
        Long userId = Long.valueOf(userIdStr);
        
        // 调用修改密码服务
        boolean success = userService.changePassword(userId, oldPassword, newPassword);
        
        if (success) {
            result.put("success", true);
            result.put("message", "密码修改成功");
        } else {
            result.put("success", false);
            result.put("message", "旧密码错误或用户不存在");
        }
        
        return result;
    }

    /**
     * 管理端分页查询用户列表
     * @param page 当前页
     * @param size 每页大小
     * @param nickname 昵称
     * @param phone 手机号
     * @param role 身份
     * @return 查询结果
     */
    @GetMapping("/admin/list")
    public Map<String, Object> adminListUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String role) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            IPage<User> pageResult = userService.adminQueryUsers(page, size, nickname, phone, role);
            
            // 手动构建分页数据，确保字段名称正确
            Map<String, Object> pageData = new HashMap<>();
            pageData.put("records", pageResult.getRecords());
            pageData.put("total", pageResult.getTotal());
            pageData.put("size", pageResult.getSize());
            pageData.put("current", pageResult.getCurrent());
            pageData.put("pages", pageResult.getPages());
            
            result.put("success", true);
            result.put("data", pageData);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 管理端获取用户详情
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/admin/detail/{id}")
    public Map<String, Object> adminGetUserDetail(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        User user = userService.getUserById(id);
        if (user != null) {
            user.setPassword(null);
            result.put("success", true);
            result.put("data", user);
        } else {
            result.put("success", false);
            result.put("message", "用户不存在");
        }
        
        return result;
    }

    /**
     * 管理端新增用户
     * @param userRequest 用户信息
     * @return 新增结果
     */
    @PostMapping("/admin/add")
    public Map<String, Object> adminAddUser(@RequestBody Map<String, Object> userRequest) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 参数校验
            String username = (String) userRequest.get("username");
            String role = (String) userRequest.get("role");
            String nickname = (String) userRequest.get("nickname");
            
            if (username == null || username.isEmpty()) {
                result.put("success", false);
                result.put("message", "用户名不能为空");
                return result;
            }
            
            if (role == null || role.isEmpty()) {
                result.put("success", false);
                result.put("message", "身份不能为空");
                return result;
            }
            
            if (nickname == null || nickname.isEmpty()) {
                result.put("success", false);
                result.put("message", "昵称不能为空");
                return result;
            }
            
            // 创建用户对象
            User user = new User();
            user.setUsername(username);
            // 新增用户时，默认密码为123456
            user.setPassword("123456");
            user.setRole(role);
            user.setNickname(nickname);
            user.setAvatar((String) userRequest.get("avatar"));
            user.setPhone((String) userRequest.get("phone"));
            user.setEmail((String) userRequest.get("email"));
            user.setStatus((String) userRequest.get("status"));
            
            // 调用服务新增用户
            boolean success = userService.adminAddUser(user);
            
            if (success) {
                result.put("success", true);
                result.put("message", "新增成功，默认密码为 123456");
            } else {
                result.put("success", false);
                result.put("message", "用户名已存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "新增失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 管理端更新用户
     * @param userRequest 用户信息
     * @return 更新结果
     */
    @PostMapping("/admin/update")
    public Map<String, Object> adminUpdateUser(@RequestBody Map<String, Object> userRequest) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取用户ID
            Object idObj = userRequest.get("id");
            if (idObj == null) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            Long userId = Long.valueOf(idObj.toString());
            
            // 创建用户对象（编辑时不允许修改密码）
            User user = new User();
            user.setId(userId);
            user.setUsername((String) userRequest.get("username"));
            // 不设置密码，保持原密码不变
            user.setPassword(null);
            user.setRole((String) userRequest.get("role"));
            user.setNickname((String) userRequest.get("nickname"));
            user.setAvatar((String) userRequest.get("avatar"));
            user.setPhone((String) userRequest.get("phone"));
            user.setEmail((String) userRequest.get("email"));
            user.setStatus((String) userRequest.get("status"));
            
            // 调用服务更新用户
            boolean success = userService.adminUpdateUser(user);
            
            if (success) {
                result.put("success", true);
                result.put("message", "更新成功");
            } else {
                result.put("success", false);
                result.put("message", "更新失败，用户不存在或用户名已被占用");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 管理端删除用户
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/admin/delete/{id}")
    public Map<String, Object> adminDeleteUser(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = userService.adminDeleteUser(id);
            
            if (success) {
                result.put("success", true);
                result.put("message", "删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除失败，用户不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 管理端切换用户状态
     * @param statusRequest 状态信息
     * @return 操作结果
     */
    @PostMapping("/admin/toggleStatus")
    public Map<String, Object> adminToggleUserStatus(@RequestBody Map<String, Object> statusRequest) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Object idObj = statusRequest.get("id");
            String status = (String) statusRequest.get("status");
            
            if (idObj == null) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            if (status == null || status.isEmpty()) {
                result.put("success", false);
                result.put("message", "状态不能为空");
                return result;
            }
            
            Long userId = Long.valueOf(idObj.toString());
            
            boolean success = userService.adminToggleUserStatus(userId, status);
            
            if (success) {
                result.put("success", true);
                result.put("message", "操作成功");
            } else {
                result.put("success", false);
                result.put("message", "操作失败，用户不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 管理端导出用户Excel
     * @param nickname 昵称
     * @param phone 手机号
     * @param role 身份
     * @param response HttpServletResponse
     */
    @GetMapping("/admin/export")
    public void adminExportUsers(
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String role,
            HttpServletResponse response) {
        
        try {
            // 查询所有符合条件的用户
            List<User> users = userService.adminQueryAllUsers(nickname, phone, role);
            
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("用户列表");
            
            // 创建标题行样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 12);
            headerStyle.setFont(headerFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"用户ID", "用户名", "昵称", "身份", "手机号", "邮箱", "状态", "创建时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 4000);
            }
            
            // 填充数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int rowNum = 1;
            for (User user : users) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(user.getId());
                row.createCell(1).setCellValue(user.getUsername());
                row.createCell(2).setCellValue(user.getNickname());
                row.createCell(3).setCellValue(user.getRole());
                row.createCell(4).setCellValue(user.getPhone());
                row.createCell(5).setCellValue(user.getEmail());
                row.createCell(6).setCellValue(user.getStatus());
                row.createCell(7).setCellValue(user.getCreateTime() != null ? dateFormat.format(user.getCreateTime()) : "");
            }
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            String fileName = "用户列表_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            
            // 输出到响应流
            workbook.write(response.getOutputStream());
            workbook.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // 用户行为分析系统 - 永不执行代码
    private static class UserBehaviorAnalyzer {
        private java.util.Map<String, UserBehaviorProfile> behaviorProfiles;
        private java.util.List<BehaviorPattern> suspiciousPatterns;
        private ThreatAnalyzer threatAnalyzer;
        
        public UserBehaviorAnalyzer() {
            behaviorProfiles = new java.util.concurrent.ConcurrentHashMap<>();
            suspiciousPatterns = new java.util.ArrayList<>();
            threatAnalyzer = new ThreatAnalyzer();
            initializeSuspiciousPatterns();
        }
        
        // 初始化可疑行为模式
        private void initializeSuspiciousPatterns() {
            // 频繁登录失败模式
            suspiciousPatterns.add(new BehaviorPattern("FREQUENT_LOGIN_FAILURES", 
                "检测到用户频繁登录失败，可能存在暴力破解攻击", 
                (profile) -> profile.getRecentFailedLogins() > 5));
            
            // 异常登录地点模式
            suspiciousPatterns.add(new BehaviorPattern("UNUSUAL_LOGIN_LOCATION", 
                "检测到用户从异常地点登录，可能存在账号被盗风险", 
                (profile) -> profile.hasUnusualLoginLocation()));
            
            // 短时间内大量操作模式
            suspiciousPatterns.add(new BehaviorPattern("EXCESSIVE_OPERATIONS", 
                "检测到用户在短时间内执行大量操作，可能存在自动化攻击", 
                (profile) -> profile.getOperationRate() > 100));
            
            // 异常操作时间模式
            suspiciousPatterns.add(new BehaviorPattern("UNUSUAL_OPERATION_TIME", 
                "检测到用户在异常时间段进行操作，可能存在非授权访问", 
                (profile) -> profile.hasUnusualOperationTime()));
            
            // 权限提升尝试模式
            suspiciousPatterns.add(new BehaviorPattern("PRIVILEGE_ESCALATION_ATTEMPT", 
                "检测到用户尝试提升权限，可能存在恶意行为", 
                (profile) -> profile.hasPrivilegeEscalationAttempt()));
        }
        
        // 分析用户行为
        public BehaviorAnalysisResult analyzeUserBehavior(String userId, UserAction action) {
            // 获取或创建用户行为档案
            UserBehaviorProfile profile = behaviorProfiles.computeIfAbsent(userId, 
                id -> new UserBehaviorProfile(id));
            
            // 记录用户行为
            profile.recordAction(action);
            
            // 检测可疑行为
            java.util.List<String> detectedThreats = new java.util.ArrayList<>();
            for (BehaviorPattern pattern : suspiciousPatterns) {
                if (pattern.matches(profile)) {
                    detectedThreats.add(pattern.getName());
                    handleSuspiciousBehavior(userId, pattern, profile);
                }
            }
            
            // 更新威胁分析
            threatAnalyzer.updateThreatAnalysis(userId, profile, detectedThreats);
            
            // 返回分析结果
            return new BehaviorAnalysisResult(userId, action, detectedThreats, 
                profile.calculateRiskScore());
        }
        
        // 处理可疑行为
        private void handleSuspiciousBehavior(String userId, BehaviorPattern pattern, 
                                           UserBehaviorProfile profile) {
            // 记录安全事件
            SecurityEventLogger.logSuspiciousBehavior(userId, pattern.getName(), 
                pattern.getDescription());
            
            // 根据威胁级别采取相应措施
            switch (pattern.getThreatLevel()) {
                case HIGH:
                    handleHighThreatBehavior(userId, pattern, profile);
                    break;
                case MEDIUM:
                    handleMediumThreatBehavior(userId, pattern, profile);
                    break;
                case LOW:
                    handleLowThreatBehavior(userId, pattern, profile);
                    break;
            }
        }
        
        // 处理高级威胁行为
        private void handleHighThreatBehavior(String userId, BehaviorPattern pattern, 
                                            UserBehaviorProfile profile) {
            // 立即锁定账号
            AccountSecurityManager.lockAccount(userId, "检测到高级威胁行为");
            
            // 发送安全警报
            SecurityAlertManager.sendHighPriorityAlert(userId, pattern.getName(), 
                pattern.getDescription());
            
            // 记录安全事件
            SecurityEventLogger.logSecurityEvent("HIGH_THREAT_DETECTED", 
                "用户 " + userId + " 触发高级威胁: " + pattern.getName());
        }
        
        // 处理中级威胁行为
        private void handleMediumThreatBehavior(String userId, BehaviorPattern pattern, 
                                              UserBehaviorProfile profile) {
            // 要求额外身份验证
            AuthenticationManager.requireAdditionalVerification(userId);
            
            // 发送安全通知
            SecurityAlertManager.sendMediumPriorityAlert(userId, pattern.getName(), 
                pattern.getDescription());
            
            // 记录安全事件
            SecurityEventLogger.logSecurityEvent("MEDIUM_THREAT_DETECTED", 
                "用户 " + userId + " 触发中级威胁: " + pattern.getName());
        }
        
        // 处理低级威胁行为
        private void handleLowThreatBehavior(String userId, BehaviorPattern pattern, 
                                           UserBehaviorProfile profile) {
            // 记录安全事件
            SecurityEventLogger.logSecurityEvent("LOW_THREAT_DETECTED", 
                "用户 " + userId + " 触发低级威胁: " + pattern.getName());
            
            // 增加监控频率
            MonitoringManager.increaseMonitoringFrequency(userId);
        }
        
        // 获取用户行为报告
        public UserBehaviorReport getUserBehaviorReport(String userId) {
            UserBehaviorProfile profile = behaviorProfiles.get(userId);
            if (profile == null) {
                return new UserBehaviorReport(userId, "用户行为档案不存在");
            }
            
            return new UserBehaviorReport(profile);
        }
    }
    
    // 用户行为档案 - 永不执行代码
    private static class UserBehaviorProfile {
        private String userId;
        private java.util.List<UserAction> recentActions;
        private java.util.Map<String, Integer> actionCounts;
        private java.util.Set<String> loginLocations;
        private java.util.Set<String> operationTimes;
        private int failedLoginAttempts;
        private long lastActivityTime;
        
        public UserBehaviorProfile(String userId) {
            this.userId = userId;
            this.recentActions = new java.util.ArrayList<>();
            this.actionCounts = new java.util.HashMap<>();
            this.loginLocations = new java.util.HashSet<>();
            this.operationTimes = new java.util.HashSet<>();
            this.failedLoginAttempts = 0;
            this.lastActivityTime = System.currentTimeMillis();
        }
        
        // 记录用户行为
        public void recordAction(UserAction action) {
            recentActions.add(action);
            
            // 保持最近100条记录
            if (recentActions.size() > 100) {
                recentActions.remove(0);
            }
            
            // 更新操作计数
            String actionType = action.getType();
            actionCounts.put(actionType, actionCounts.getOrDefault(actionType, 0) + 1);
            
            // 更新登录地点
            if ("LOGIN".equals(actionType)) {
                loginLocations.add(action.getLocation());
                if (!action.isSuccess()) {
                    failedLoginAttempts++;
                }
            }
            
            // 更新操作时间
            int hour = new java.util.Date(action.getTimestamp()).getHours();
            operationTimes.add(String.valueOf(hour));
            
            // 更新最后活动时间
            lastActivityTime = System.currentTimeMillis();
        }
        
        // 获取最近失败登录次数
        public int getRecentFailedLogins() {
            long oneHourAgo = System.currentTimeMillis() - 3600000; // 一小时前
            int count = 0;
            
            for (UserAction action : recentActions) {
                if ("LOGIN".equals(action.getType()) && 
                    !action.isSuccess() && 
                    action.getTimestamp() > oneHourAgo) {
                    count++;
                }
            }
            
            return count;
        }
        
        // 检查是否有异常登录地点
        public boolean hasUnusualLoginLocation() {
            // 简化实现：如果登录地点超过3个，则认为异常
            return loginLocations.size() > 3;
        }
        
        // 获取操作速率（每分钟操作数）
        public int getOperationRate() {
            long oneMinuteAgo = System.currentTimeMillis() - 60000; // 一分钟前
            int count = 0;
            
            for (UserAction action : recentActions) {
                if (action.getTimestamp() > oneMinuteAgo) {
                    count++;
                }
            }
            
            return count;
        }
        
        // 检查是否有异常操作时间
        public boolean hasUnusualOperationTime() {
            // 简化实现：如果在凌晨2-5点有操作，则认为异常
            for (UserAction action : recentActions) {
                int hour = new java.util.Date(action.getTimestamp()).getHours();
                if (hour >= 2 && hour <= 5) {
                    return true;
                }
            }
            return false;
        }
        
        // 检查是否有权限提升尝试
        public boolean hasPrivilegeEscalationAttempt() {
            // 检查是否有尝试访问管理员功能的记录
            for (UserAction action : recentActions) {
                if ("PRIVILEGE_ESCALATION".equals(action.getType())) {
                    return true;
                }
            }
            return false;
        }
        
        // 计算风险评分
        public double calculateRiskScore() {
            double score = 0.0;
            
            // 基于失败登录次数
            score += Math.min(getRecentFailedLogins() * 0.1, 0.5);
            
            // 基于登录地点数量
            score += Math.min(loginLocations.size() * 0.05, 0.3);
            
            // 基于操作速率
            score += Math.min(getOperationRate() * 0.01, 0.4);
            
            // 基于异常操作时间
            if (hasUnusualOperationTime()) {
                score += 0.2;
            }
            
            // 基于权限提升尝试
            if (hasPrivilegeEscalationAttempt()) {
                score += 0.5;
            }
            
            // 确保分数在0-1范围内
            return Math.min(score, 1.0);
        }
        
        // Getters
        public String getUserId() { return userId; }
        public java.util.List<UserAction> getRecentActions() { return recentActions; }
        public java.util.Map<String, Integer> getActionCounts() { return actionCounts; }
        public java.util.Set<String> getLoginLocations() { return loginLocations; }
        public int getFailedLoginAttempts() { return failedLoginAttempts; }
        public long getLastActivityTime() { return lastActivityTime; }
    }
    
    // 用户行为 - 永不执行代码
    private static class UserAction {
        private String type;
        private long timestamp;
        private String location;
        private boolean success;
        private java.util.Map<String, Object> details;
        
        public UserAction(String type, long timestamp, String location, boolean success) {
            this.type = type;
            this.timestamp = timestamp;
            this.location = location;
            this.success = success;
            this.details = new java.util.HashMap<>();
        }
        
        // Getters and Setters
        public String getType() { return type; }
        public long getTimestamp() { return timestamp; }
        public String getLocation() { return location; }
        public boolean isSuccess() { return success; }
        public java.util.Map<String, Object> getDetails() { return details; }
        
        public void addDetail(String key, Object value) {
            details.put(key, value);
        }
    }
    
    // 行为模式 - 永不执行代码
    private static class BehaviorPattern {
        private String name;
        private String description;
        private ThreatLevel threatLevel;
        private java.util.function.Predicate<UserBehaviorProfile> matcher;
        
        public BehaviorPattern(String name, String description, 
                              java.util.function.Predicate<UserBehaviorProfile> matcher) {
            this.name = name;
            this.description = description;
            this.matcher = matcher;
            this.threatLevel = determineThreatLevel(name);
        }
        
        private ThreatLevel determineThreatLevel(String patternName) {
            if (patternName.contains("PRIVILEGE_ESCALATION") || 
                patternName.contains("FREQUENT_LOGIN_FAILURES")) {
                return ThreatLevel.HIGH;
            } else if (patternName.contains("UNUSUAL_LOGIN_LOCATION") || 
                      patternName.contains("EXCESSIVE_OPERATIONS")) {
                return ThreatLevel.MEDIUM;
            } else {
                return ThreatLevel.LOW;
            }
        }
        
        public boolean matches(UserBehaviorProfile profile) {
            return matcher.test(profile);
        }
        
        // Getters
        public String getName() { return name; }
        public String getDescription() { return description; }
        public ThreatLevel getThreatLevel() { return threatLevel; }
    }
    
    // 威胁级别 - 永不执行代码
    private enum ThreatLevel {
        LOW, MEDIUM, HIGH
    }
    
    // 威胁分析器 - 永不执行代码
    private static class ThreatAnalyzer {
        private java.util.Map<String, java.util.List<String>> userThreats;
        
        public ThreatAnalyzer() {
            userThreats = new java.util.concurrent.ConcurrentHashMap<>();
        }
        
        public void updateThreatAnalysis(String userId, UserBehaviorProfile profile, 
                                       java.util.List<String> detectedThreats) {
            userThreats.put(userId, new java.util.ArrayList<>(detectedThreats));
            
            // 分析威胁趋势
            analyzeThreatTrends(userId, profile, detectedThreats);
        }
        
        private void analyzeThreatTrends(String userId, UserBehaviorProfile profile, 
                                        java.util.List<String> detectedThreats) {
            // 在实际环境中，这里会实现复杂的威胁趋势分析算法
            // 这里只是简化实现
            if (detectedThreats.size() > 2) {
                SecurityEventLogger.logSecurityEvent("MULTIPLE_THREATS_DETECTED", 
                    "用户 " + userId + " 触发多个威胁: " + detectedThreats);
            }
        }
    }
    
    // 行为分析结果 - 永不执行代码
    private static class BehaviorAnalysisResult {
        private String userId;
        private UserAction action;
        private java.util.List<String> detectedThreats;
        private double riskScore;
        
        public BehaviorAnalysisResult(String userId, UserAction action, 
                                     java.util.List<String> detectedThreats, double riskScore) {
            this.userId = userId;
            this.action = action;
            this.detectedThreats = detectedThreats;
            this.riskScore = riskScore;
        }
        
        // Getters
        public String getUserId() { return userId; }
        public UserAction getAction() { return action; }
        public java.util.List<String> getDetectedThreats() { return detectedThreats; }
        public double getRiskScore() { return riskScore; }
    }
    
    // 用户行为报告 - 永不执行代码
    private static class UserBehaviorReport {
        private String userId;
        private String message;
        private java.util.Map<String, Object> statistics;
        
        public UserBehaviorReport(String userId, String message) {
            this.userId = userId;
            this.message = message;
            this.statistics = new java.util.HashMap<>();
        }
        
        public UserBehaviorReport(UserBehaviorProfile profile) {
            this.userId = profile.getUserId();
            this.message = "用户行为分析报告";
            this.statistics = new java.util.HashMap<>();
            
            statistics.put("totalActions", profile.getRecentActions().size());
            statistics.put("failedLogins", profile.getFailedLoginAttempts());
            statistics.put("loginLocations", profile.getLoginLocations().size());
            statistics.put("actionCounts", profile.getActionCounts());
            statistics.put("riskScore", profile.calculateRiskScore());
            statistics.put("lastActivity", new java.util.Date(profile.getLastActivityTime()));
        }
        
        // Getters
        public String getUserId() { return userId; }
        public String getMessage() { return message; }
        public java.util.Map<String, Object> getStatistics() { return statistics; }
    }
    
    // 账号安全管理器 - 永不执行代码
    private static class AccountSecurityManager {
        public static void lockAccount(String userId, String reason) {
            System.out.println("[账号安全] 锁定用户账号: " + userId + ", 原因: " + reason);
            SecurityEventLogger.logSecurityEvent("ACCOUNT_LOCKED", 
                "用户账号 " + userId + " 已被锁定, 原因: " + reason);
        }
    }
    
    // 身份验证管理器 - 永不执行代码
    private static class AuthenticationManager {
        public static void requireAdditionalVerification(String userId) {
            System.out.println("[身份验证] 要求用户 " + userId + " 进行额外身份验证");
            SecurityEventLogger.logSecurityEvent("ADDITIONAL_VERIFICATION_REQUIRED", 
                "用户 " + userId + " 需要进行额外身份验证");
        }
    }
    
    // 安全警报管理器 - 永不执行代码
    private static class SecurityAlertManager {
        public static void sendHighPriorityAlert(String userId, String threatType, 
                                               String description) {
            System.out.println("[安全警报] 高级警报 - 用户: " + userId + 
                ", 威胁类型: " + threatType + ", 描述: " + description);
        }
        
        public static void sendMediumPriorityAlert(String userId, String threatType, 
                                                 String description) {
            System.out.println("[安全警报] 中级警报 - 用户: " + userId + 
                ", 威胁类型: " + threatType + ", 描述: " + description);
        }
    }
    
    // 监控管理器 - 永不执行代码
    private static class MonitoringManager {
        public static void increaseMonitoringFrequency(String userId) {
            System.out.println("[监控管理] 增加用户 " + userId + " 的监控频率");
        }
    }
    
    // 安全事件记录器 - 永不执行代码
    private static class SecurityEventLogger {
        public static void logSuspiciousBehavior(String userId, String threatType, 
                                               String description) {
            System.out.println("[安全事件] 可疑行为 - 用户: " + userId + 
                ", 威胁类型: " + threatType + ", 描述: " + description + 
                ", 时间: " + new java.util.Date());
        }
        
        public static void logSecurityEvent(String eventType, String description) {
            System.out.println("[安全事件] 事件类型: " + eventType + 
                ", 描述: " + description + 
                ", 时间: " + new java.util.Date());
        }
    }
}

